<template>
	<view class="annot-box">
		<view class="image-box">
			<image id="image" :src="imageUrl" style="width: 100%;" mode="widthFix" @load="imageLoaded"></image>
			<template v-if="showRects">
				<view
					v-for="(item, idx) in rects"
					:key="idx"
					class="rect"
					:style="{
						top: item.top * scaleY + 'px',
						left: item.left * scaleX + 'px',
						width: item.width * scaleX + 'px',
						height: item.height * scaleY + 'px',
						borderColor: item.color || getColor(idx)
					}"
				>
					<!-- <view class="rect-label">{{ item.index || idx + 1 }}</view> -->
				</view>
			</template>
		</view>
		<view class="opeartion">
			<view class="radio" v-if='false'>
				<radio-group @change="handleSelectAll">
					<label style="margin-right: 24rpx;">
						<radio :value="true" :checked="selectAll" /><text>全选</text>
					</label>
					<label>
						<radio :value="false" :checked="!selectAll" /><text>取消全选</text>
					</label>
				</radio-group>
			</view>
			<view class="insect-sort">
				<view class="title">
					害虫分类统计
				</view>
				<view 
					class="sort" 
					v-for="(insect, index) in insectStatistics" 
					:key="index"
				>
					<view style="display: flex;align-items: center;">
						<view class="sort-color" :style="{backgroundColor: insect.color || getColor(index)}"></view>
						<view>
							{{ insect.name || `标注 ${insect.index || index + 1}` }}
						</view>
					</view>
					<view class="insect-num">
						<text>数量：</text>
						<text style="color:#0084ff">{{ insect.count }}</text>
					</view>
				</view>
			</view>
		</view>
		<view class="select-tag-btn" @click="selectTag">
			选择标签
		</view>
	</view>
</template>

<script>
	import { getByAttachmentId } from '../../untils/api.js'
	export default {
		data() {
			return {
				imageUrl: '',
				showRects:true,
				imageInfo: {
					width: 0,
					height: 0,
					realWidth: 0,
					realHeight: 0
				},
				scaleX: 1,
				scaleY: 1,
				selectAll: true,
				rects: [],
				colors: ['#FF0000', '#00FF00', '#0000FF', '#FFFF00', '#FF00FF', '#00FFFF']
			};
		},
		computed: {
		    insectStatistics() {
		        const stats = {};
		        this.rects.forEach(rect => {
		            const key = rect.name || '未命名';
		            if (!stats[key]) {
		                stats[key] = {
		                    name: rect.name || '未命名',
		                    count: 0,
		                    color: rect.color || rect.bgColor
		                };
		            }
		            stats[key].count++;
		        });
		        return Object.values(stats);
		    }
		},
		methods: {
			getDetail(id) {
			    getByAttachmentId({attachmentId: id}).then(res => {
			        if (res.data && res.data.length > 0) {
			            const content = res.data[0].annotatedContent || res.data[0].annotatedContent;
			            let rawRects = [];
			            try {
			                const arr = typeof content === 'string' ? JSON.parse(content) : content;
			                // 扁平化所有location
			                arr.forEach(item => {
			                    if (Array.isArray(item.location)) {
			                        item.location.forEach(loc => {
			                            rawRects.push({
			                                ...loc,
			                                name: item.name,
			                                bgColor: item.bgColor
			                            });
			                        });
			                    }
			                });
			                this.rects = rawRects;
			            } catch (e) {
			                console.error('解析标注数据失败:', e);
			                this.rects = [];
			            }
			        } else {
			            this.rects = [];
			        }
			    }).catch(err => {
			        console.error('获取标注数据失败:', err);
			        this.rects = [];
			    });
			},
			selectTag() {
				uni.navigateTo({
					url: '/subpackage/insect/tags'
				});
			},
			handleSelectAll(e) {
				this.showRects = e.detail.value === 'true';
			},
			imageLoaded(e) {
			    uni.getImageInfo({
			      src: this.imageUrl,
			      success: (res) => {
			        this.imageInfo.realWidth = res.width;
			        this.imageInfo.realHeight = res.height;
			        
			        // 使用setTimeout确保DOM更新完成
			        setTimeout(() => {
			          const query = uni.createSelectorQuery().in(this);
			          query.select('#image').boundingClientRect(data => {
						  console.log(this.imageInfo,data,'this.imageInfo');
			            if (data) {
			              this.imageInfo.width = data.width;
			              this.imageInfo.height = data.height;
			              
			              // 计算缩放比例
			              this.scaleX = this.imageInfo.width / this.imageInfo.realWidth;
			              this.scaleY = this.scaleX;
			              console.log('缩放比例:', this.scaleX, this.scaleY);
						  console.log(this.rects);
			            } else {
			              console.warn('获取图片显示尺寸失败，使用默认比例');
			              this.scaleX = 1;
			              this.scaleY = 1;
			            }
			          }).exec();
			        }, 100);
			      },
			      fail: (err) => {
			        console.error('获取图片信息失败:', err);
			        this.scaleX = 1;
			        this.scaleY = 1;
			      }
			    });
			},
			getColor(index) {
				return this.colors[index % this.colors.length];
			}
		},
		onLoad(param) {
			console.log('页面参数:', param);
			this.imageUrl = param.url;
			if (param.attachmentId) {
				this.getDetail(param.attachmentId);
			}
			
			// 测试数据 - 实际使用时可以删除
			// this.rects = [{
			// 	type: "rect",
			// 	left: 1094.2237061769615,
			// 	top: 479.59933222036733,
			// 	width: 205.54257095158604,
			// 	height: 205.542570951586,
			// 	color: "#F83315",
			// 	index: 1
			// }];
		}
	}
</script>

<style lang="scss" scoped>
	.annot-box {
		height: 100vh;
		width: 100%;
		background: #f4f5f5;
		overflow: hidden;
		display: flex;
		flex-direction: column;
		
		.image-box {
			position: relative;
			width: 100%;
			flex-shrink: 0;
			
			.rect {
				position: absolute;
				border: 3rpx solid;
				box-sizing: border-box;
				z-index: 10;
				display: flex;
				justify-content: center;
				align-items: flex-start;
				
				.rect-label {
					position: relative;
					top: -40rpx;
					background: rgba(0,0,0,0.7);
					color: #fff;
					font-size: 24rpx;
					padding: 4rpx 12rpx;
					border-radius: 8rpx;
					white-space: nowrap;
				}
			}
		}
		
		.opeartion {
			flex: 1;
			overflow-y: auto;
			width: 100%;
			background-color: #fff;
			padding: 24rpx 0 ;
			
			.radio {
				padding: 0 24rpx;
				margin-bottom: 24rpx;
			}
			
			.insect-sort {
				padding: 0 24rpx;
				.title {
					font-size: 32rpx;
					font-weight: bold;
					margin-bottom: 24rpx;
				}
				
				.sort {
					display: flex;
					justify-content: space-between;
					align-items: center;
					padding: 16rpx 0;
					border-bottom: 1rpx solid #eee;
					
					.sort-color {
						width: 28rpx;
						height: 28rpx;
						margin-right: 16rpx;
					}
				}
				
				.insect-num {
					color: #98c4e9;
				}
			}
		}
		
		.select-tag-btn {
			position: fixed;
			bottom: 40rpx;
			right: 40rpx;
			background-color: #007AFF;
			color: white;
			padding: 16rpx 32rpx;
			border-radius: 50rpx;
			box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.2);
			z-index: 100;
		}
	}
</style>